<?php

namespace app\modules\test\controllers;

use app\models\GoodsInfo;
use app\models\GoodsTags;
use app\models\Images;
use app\models\ImagesCates;
use app\models\ItemImageMapping;
use app\models\Product;
use app\models\ProductItem;
use app\models\TagLinkProduct;
use yii;
use app\core\YpBaseController;
use app\models\AdminLogger;
use app\extensions\XUtils;
use app\services\ProductSyncService;

class IndexController extends YpBaseController
{
    /*public function actions()
    {
        return [
            'Kupload' => [
                'class' => 'pjkui\kindeditor\KindEditor',
            ]
        ];
    }*/

    public function actionIndex()
    {
        //DAO方式
        $list = (new \yii\db\Query())
            ->select(['id', 'userId', 'catalog', 'url', 'intro', 'ip', 'createTime', 'isDetail'])
            ->from('gds_admin_logger')
            ->where(['isDetail' => '0'])
            ->limit(10)
            ->all();
        /*echo "<pre>";
        print_r($list);
        echo "</pre>";*/
        //query-builder方式
        $list = Yii::$app->db->createCommand('SELECT * FROM gds_admin_logger where isDetail=:isDetail limit 10')
            ->bindValue(':isDetail', 0)
            ->queryAll();

        /* echo "<pre>";
         print_r($list);
         echo "</pre>";*/

        $model = new AdminLogger();
        $list  = $model::find()
            ->where(['isDetail' => 0])
            ->asArray()
            ->orderBy('id')
            ->limit(10)
            ->all();
        echo '<pre>';
        print_r($list);
        echo '</pre>';
    }

    public function actionKindeditor()
    {
        //echo \pjkui\kindeditor\KindEditor::widget([]);die;
        return $this->render('kindeditor');
    }

    public function actionProductpicture()
    {
        $productModel          = new Product();
        $productItemModel      = new ProductItem();
        $itemImageMappingModel = new ItemImageMapping();
        $page                  = Yii::$app->request->get('page', 1);
        $count                 = $productModel->dbCount();
        $totalPage             = ceil($count / 1000);
        if ($page > $totalPage) {
            var_dump('数据已跑完！！');
            exit;
        }
        $params      = [
            'page'  => $page,
            'limit' => 1000,
            'where' => [
                'and',
                ['>', 'id', 0],
            ],
            'order' => 'id ASC'
        ];
        $productList = $productModel->dbList(['id', 'productPackageId'], $params);
        foreach ($productList['list'] as $data) {
            $productImagePrepare = [];
            if (!empty($data['productPackageId'])) {
                $productItemList = $productItemModel->dbList(['id', 'itemId', 'isMainItem', 'productPackageId', 'newProductPackageId'], ['where' => ['productPackageId' => $data['productPackageId']]]);
            } else {
                $productItemList = $productItemModel->dbList(['id', 'itemId', 'isMainItem', 'productPackageId', 'newProductPackageId'], ['where' => ['newProductPackageId' => $data['id']]]);
            }
            foreach ($productItemList['list'] as $key => $list) {
                $itemImageMapping = $itemImageMappingModel->fetchImage(['itemId' => $list['itemId']]);
                if ($itemImageMapping['objectId']) {
                    if (empty($itemImageMapping['url'])) {
                        $itemImageMapping['url'] = '/static/img/photo_default.png';
                    } else {
                        $itemImageMapping['url'] = (isset(Yii::$app->params['magImageUrl']) ? Yii::$app->params['magImageUrl'] : 'http://cdn.yaochufa.com/') . $itemImageMapping['url'];
                    }
                }
                $productImagePrepare[ $key ]['url'] = $itemImageMapping['url'];
            }
            $picture                    = serialize($productImagePrepare);
            $updateData['picture']      = $picture;
            $updateData['modifiedDate'] = time();
            $affect                     = $productModel->dbUpdate('', $updateData, ['where' => 'id=:id', 'bind' => [':id' => $data['id']]]);
            if ($affect) {
                var_dump($data['productPackageId'] . '产品图片更新成功</br>');
            } else {
                var_dump($data['productPackageId'] . '产品图片更新失败</br>');
            }
        }
        XUtils::message('success', "第{$page}页数据更新成功！", '/test/index/productpicture?page=' . ($page + 1));
    }

    public function actionGoodspicture()
    {
        $imagesModel    = new Images();
        $goodsInfoModel = new GoodsInfo();
        $imageCateModel = new ImagesCates();
        $page           = Yii::$app->request->get('page', 1);
        $count          = $goodsInfoModel->dbCount();
        $totalPage      = ceil($count / 1000);
        if ($page > $totalPage) {
            var_dump('数据已跑完！！');
            exit;
        }

        $imageCateList = $imageCateModel->dbList('*', ['where' => ['and', ['>', 'cateId', 0]], 'order' => 'cateId DESC']);
        $params        = [
            'page'  => $page,
            'limit' => 1000,
            'where' => [
                'and',
                ['>', 'id', 0],
            ],
            'order' => 'id ASC'
        ];
        $goodsInfoList = $goodsInfoModel->dbList(['id', 'channelLinkId', 'hotelScenicId', 'picture'], $params);
        foreach ($goodsInfoList['list'] as $data) {
            $goodsImagePrepare = [];
            $pictureArray      = [];
            foreach ($imageCateList['list'] as $cate) {
                $cateId    = $cate['cateId'];
                $imageList = $imagesModel->dbList(['url', 'imageId', 'imageCategoryId'], ['where' => ['and', 'imageCategoryId=:imageCategoryId', 'objectId=:objectId'], 'bind' => [':imageCategoryId' => $cateId, ':objectId' => $data['hotelScenicId']], 'order' => 'sortOrder DESC']);
                foreach ($imageList['list'] as $key => $value) {
                    if (empty($value['url'])) {
                        $goodsImagePrepare[ $key ]['url'] = $value['url'] = '/static/img/photo_default.png';
                    } else {
                        $goodsImagePrepare[ $key ]['url'] = (isset(Yii::$app->params['magImageUrl']) ? Yii::$app->params['magImageUrl'] : 'http://cdn.yaochufa.com/') . $value['url'];
                    }
                }
            }
            if (!empty($data['picture'])) {
                $pictureArray = unserialize($data['picture']);
            }
            $pictureArray[ $cateId ]  = $goodsImagePrepare;
            $picture                  = serialize($pictureArray);
            $updateData['picture']    = $picture;
            $updateData['updateTime'] = time();
            $affect                   = $goodsInfoModel->dbUpdate('', $updateData, ['where' => 'id=:id', 'bind' => [':id' => $data['id']]]);
            if ($affect) {
                var_dump($data['channelLinkId'] . '商品图片更新成功</br>');
            } else {
                var_dump($data['channelLinkId'] . '商品图片更新失败</br>');
            }
        }
        XUtils::message('success', "第{$page}页数据更新成功！", '/test/index/goodspicture?page=' . ($page + 1));
    }

    public function actionGoodsorder()
    {
        $goodsTagsModel = new GoodsTags();
        $page           = Yii::$app->request->get('page', 0);
        if ($page == 1) {
            $totalPage = 1;
        } else {
            $count     = $goodsTagsModel->dbCount();
            $totalPage = ceil($count / 1000);
        }
        $dataSet          = [];//保存同一channelLinkId的childTagId数组
        $channelOrderData = [];//保存同一channelLinkId的最大排序值
        for ($i = 1; $i <= $totalPage; $i++) {
            $params        = [
                'page'  => $i,
                'limit' => 1000,
                'where' => [
                    'and',
                    ['>', 'id', 0],
                ],
                'order' => 'id ASC'
            ];
            $goodsTagsList = $goodsTagsModel->dbList('*', $params);
            foreach ($goodsTagsList['list'] as $data) {
                $updateData = [];
                //判断是否存在键值为$data['channelLinkId']的数组
                if (key_exists($data['channelLinkId'], $dataSet)) {
                    if (isset($dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ])) {
                        //如果设置了数组的话，就是说明后面的数据跟前面有重复，直接读取前面的数据
                        $updateData['orderBy']    = $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['orderBy'];
                        $updateData['orderTime']  = $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['orderTime'];
                        $updateData['updateTime'] = $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['updateTime'];
                    } else {
                        //没有设置数据，则加入到数组中，获取最大数组+1作为排序
                        $channelOrderData[ $data['channelLinkId'] ] += 1;
                        $updateData['orderTime']                                                = $updateData['updateTime'] = time();
                        $updateData['orderBy']                                                  = $channelOrderData[ $data['channelLinkId'] ];
                        $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['childTagId'] = $data['childTagId'];
                        $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['orderBy']    = $updateData['orderBy'];
                        $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['orderTime']  = $updateData['orderTime'];
                        $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['updateTime'] = $updateData['updateTime'];
                    }
                } else {
                    $updateData['orderTime']                                                = $updateData['updateTime'] = time();
                    $channelOrderData[ $data['channelLinkId'] ]                             = 1;
                    $updateData['orderBy']                                                  = $channelOrderData[ $data['channelLinkId'] ];
                    $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['orderBy']    = $updateData['orderBy'];
                    $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['childTagId'] = $data['childTagId'];
                    $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['orderTime']  = $updateData['orderTime'];
                    $dataSet[ $data['channelLinkId'] ][ $data['childTagId'] ]['updateTime'] = $updateData['updateTime'];
                }
                $affect = $goodsTagsModel->dbUpdate('', $updateData, ['where' => 'id=:id', 'bind' => [':id' => $data['id']]]);
                if ($affect) {
                    var_dump($data['id'] . '商品排序更新成功</br>');
                } else {
                    var_dump($data['id'] . '商品排序更新失败</br>');
                }
            }
        }
        var_dump('数据已跑完！！');
        exit;
    }

    /**
     * 更新标签关联产品列表表productPackageId
     * @author Jacent<liangjiaxing@yaochufa.com>
     * @date 2016.11.21
     */
    public function actionPackageid()
    {
        $tagLinkProductModel = new TagLinkProduct();
        $productModel        = new Product();
        $count               = $tagLinkProductModel->dbCount();
        $totalPage           = ceil($count / 1000);
        for ($i = 1; $i <= $totalPage; $i++) {
            $params             = [
                'page'  => $i,
                'limit' => 1000,
                'where' => [
                    'and',
                    ['>', 'id', 0],
                ],
                'order' => 'id ASC'
            ];
            $tagLinkProductList = $tagLinkProductModel->dbList('*', $params);
            foreach ($tagLinkProductList['list'] as $data) {
                $updateData                     = [];
                $product                        = $productModel->dbGet(['id', 'productPackageId'], '', ['where' => ['id' => $data['productId']]]);
                $updateData['productPackageId'] = isset($product['productPackageId']) ? $product['productPackageId'] : 0;
                $affect                         = $tagLinkProductModel->dbUpdate('', $updateData, ['where' => 'id=:id', 'bind' => [':id' => $data['id']]]);
                if ($affect) {
                    var_dump($data['id'] . '标签关联产品列表productPackageId更新成功</br>');
                } else {
                    var_dump($data['id'] . '标签关联产品列表productPackageId更新失败</br>');
                }
            }
        }
        var_dump('数据已跑完！！');
        exit;
    }

    /*
    *  更细字段脚本
    */
    public function actionUpdatecolumn()
    {
        //ProductSyncService::newProductIdTwo();//更新新套餐id
        ProductSyncService::updateIntro();//更新产品文案字段
        ProductSyncService::updateProductType();//更新产品类型
        //ProductSyncService::findAutoPackageId();//给元素找系统自动打包单元素套餐
    }

    public function actionAllproductpackagemapping(){
        $type = 1;
        ProductSyncService::allProductPackageMapping($type);
    }
}
